#pragma once
#include <iostream>
#include <pthread.h>
#include <string>
#include <functional>

namespace my
{
    using func_t = std::function<void(const std::string &)>;

    class Thread
    {
        // typedef void (*func_t)(std::string str);

    public:
        Thread(std::string &&name, func_t func) : _threadName(name), _tid(0), _isRunning(false), _func(func)
        {
        }

        Thread(std::string &name, func_t func) : _threadName(name), _tid(0), _isRunning(false), _func(func)
        {
        }

        static void *ThreadRoutine(void *arg)
        {
            Thread *self = static_cast<Thread *>(arg);
            self->Execute();
            return nullptr;
        }

        bool Start()
        {
            int n = ::pthread_create(&_tid, nullptr, ThreadRoutine, this);
            if (n != 0)
                return false;
            else
                return true;
        }

        void Exit()
        {
            if (_isRunning)
            {
                ::pthread_cancel(_tid);
                _isRunning = false;
            }
        }

        void Join()
        {
            ::pthread_join(_tid, nullptr);
        }

        ~Thread()
        {
        }

    private:
        void Execute()
        {
            _isRunning = true;
            _func(_threadName);
            _isRunning = false;
        }

    private:
        std::string _threadName;
        pthread_t _tid;
        bool _isRunning;
        func_t _func;
    };
}